import {SerialPort}  from 'serialport'
import  {InterByteTimeoutParser} from '@serialport/parser-inter-byte-timeout'

class MingSerialPort {
    static sendCallback=()=>{};
    static messageEvent=(m)=>{return 0}
    constructor(com) {
        let brand=115200;
        this.options={ path: com, baudRate: brand };
        this.sp = new SerialPort( this.options);
        console.log(`connect ${com} ${brand}`)
        MingSerialPort.messageEvent=(m)=>{
            if(MingSerialPort.sendCallback!=null){
                MingSerialPort.sendCallback(m);
                MingSerialPort.sendCallback=null;
            }
        };
        this.rtsPort=1;
        this.parser = this.sp.pipe(new InterByteTimeoutParser({ interval: 1,maxBufferSize:50 }))
        this.init();
    }

    init(){
        this.parser.on('data', async (v) => {
            MingSerialPort.messageEvent(v);
        });
    }


    async usartSend(m){
        return new Promise((resolve => {
            this.sp.write(m);
            this.sp.drain(err => {
                if (err) resolve(-1);
                resolve(0);
            });
        }))
    }

    setRtsPort(v){
        this.rtsPort=v;
        if(v==1){
            v=false;
        }else {
            v=true;
        }
        this.sp.set({  rts:v})
    }

    async send(param){
        let that=this;
        return new Promise(
            async function (reslove) {
                await that.usartSend(param);
                MingSerialPort.sendCallback=(v)=>{
                    reslove(v);
                }
                setTimeout(()=>{
                    reslove(0);
                },2000)
            }
        )
    }
}

export default MingSerialPort;